package com.luckku.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luckku.boot.common.exception.ApiAsserts;
import com.luckku.boot.jwt.JwtUtil;
import com.luckku.boot.mapper.UserMapper;
import com.luckku.boot.model.dto.LoginDTO;
import com.luckku.boot.model.dto.RegisterDTO;
import com.luckku.boot.model.entity.User;
import com.luckku.boot.service.IUserService;
import com.luckku.boot.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * @author luckku
 * @date 2021/8/27
 */

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public User executeRegister(RegisterDTO dto) {
        //查询是否有相同用户名的用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, dto.getAccount()).or().eq(User::getEmail, dto.getEmail());
        User user = baseMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(user)) {
            ApiAsserts.fail("账号或手机号已存在！");
        }
        User addUser = User.builder()
                .account(dto.getAccount())
                .password(MD5Utils.getPwd(dto.getPassword()))
                .email(dto.getEmail())
                .build();
        baseMapper.insert(addUser);

        return addUser;
    }
    @Override
    public User getUserByAccount(String account) {
        return baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccount, account));
    }
    @Override
    public String executeLogin(LoginDTO dto) {
        String token = null;
        try {
            User user = getUserByAccount(dto.getAccount());
            String encodePwd = MD5Utils.getPwd(dto.getPassword());
            if(!encodePwd.equals(user.getPassword()))
            {
                throw new Exception("密码错误");
            }
            token = JwtUtil.generateToken(String.valueOf(user.getAccount()));
        } catch (Exception e) {
            log.warn("用户不存在or密码验证失败=======>{}", dto.getAccount());
        }
        return token;
    }
    //@Override
    //public ProfileVO getUserProfile(String id) {
    //    ProfileVO profile = new ProfileVO();
    //    User user = baseMapper.selectById(id);
    //    BeanUtils.copyProperties(user, profile);
    //    return profile;
    //}
}
